package cn.com.wxd.service.zookeeper.consumers;

import java.util.List;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.common.CharUtil;
import cn.com.wxd.common.GlobalConstant;

/**
 * Title:
 * Description:
 * <p>
 * Company: Amumu系统
 * Copyright: Copyright (c) 2017
 * All right reserved.
 * Created by WangXuDong on 2017/8/22.
 *
 * @author WangXuDong
 * @version 1.0
 */
public class Consumers {

    private static final Logger log = LoggerFactory.getLogger(Consumers.class);

    /**
     * 随机获取一个已注册的服务集群中
     * @param zk
     * @param serverName
     * @param watch
     * @return
     * @throws Exception
     */
    public static String getRandomService(ZooKeeper zk, String serverName, boolean watch)
            throws Exception {
        List<String> servlist = getServices(zk, serverName, watch);
        if (servlist == null | servlist.size() <= 0) {
            log.warn("无法获取一个服务连接，因为没有该服务的提供者!" + serverName);
            throw new Exception("无法提供名称为：" + serverName + "的服务!");
        }
        return servlist.get(CharUtil.getIntRanNumber(1, servlist.size()));
    }

    /**
     * 根据服务的名字获取该服务的所有集群中的服务
     *
     * @param zk
     * @param serverName
     * @param watch
     */
    public static List<String> getServices(ZooKeeper zk, String serverName, boolean watch)
            throws KeeperException, InterruptedException {
        //注册服务,并返回注册好的地址
        return zk.getChildren(GlobalConstant.ZOOKEEPERROOTNODE + "/server/" + serverName, watch);
    }

    /**
     * 获取所有子节点
     *
     * @param zk
     * @param path
     * @param watch
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    public static List<String> getChildren(ZooKeeper zk, String path, boolean watch)
            throws KeeperException, InterruptedException {
        return zk.getChildren(path, watch);
    }

    /**
     * 获取节点数据
     *
     * @param zk
     * @param path
     *
     * @return
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    public byte[] getData(ZooKeeper zk, String path) throws KeeperException, InterruptedException {
        return zk.getData(path, false, null);
    }

    /**
     * 修改节点数据
     */
    public Stat setDate(ZooKeeper zk, String path, byte[] data, int version)
            throws KeeperException, InterruptedException {
        return zk.setData(path, data, version);
    }

    /**
     * 删除节点
     */
    public void deleteNode(ZooKeeper zk, final String path, int version) throws InterruptedException, KeeperException {
        zk.delete(path, version);
    }
}
